<template>
    <div class="app-container course course-list">
      <div class="filter-container">
        <div class="filter-block">
          <span>标题：</span>
          <el-input size="small" maxlength="30"  v-model="listQuery.title" @keyup.enter.native="fetchData(true) "/>
        </div>

        <div class="filter-block">
          <span>创建时间：</span>
          <!--<el-input size="small"  @keyup.enter.native="fetchData(true)"/>-->
          <el-date-picker
            :picker-options="pickerOptionsBeginTime"
            @change="changeCreateBeginTime"
            style="margin-right: 10px"
            v-model="listQuery.createBeginTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择">
          </el-date-picker>
          至
          <el-date-picker
            :picker-options="pickerOptionsEndTime"
            @change="changeCreateEndTime"
            style="margin-left: 10px"
            v-model="listQuery.createEndTime"
            type="date"
            value-format="yyyy-MM-dd 23:59:59"
            placeholder="请选择">
          </el-date-picker>
        </div>

        <div class="filter-block">
        <span>学科：</span>
        <el-select clearable size="small" v-model="listQuery.checkedSubject" clearable @change="fetchData(true)" >
          <el-option v-for="item in subjectList" :key="item.subjectId" :label="item.subjectName" :value="item.subjectId"/>
        </el-select>
      </div>

        <div class="filter-block">
          <span>学期：</span>
          <el-select clearable style="width: 220px" size="small" v-model="listQuery.checkedSemester" clearable @change="handleChangeSemester()" >
            <el-option v-for="item in schoolSemesterList"
                       :key="item.code"
                       :label="item.label"
                       :value="item.code"/>
          </el-select>
        </div>
        <div class="filter-block">
          <span>年级：</span>
          <el-select clearable size="small" v-model="listQuery.checkedGrade" @change="handleCheckedGrade" >
            <el-option v-for="item in gradeTypeData" :key="item.distanceYear" :label="item.name" :value="item.distanceYear"/>
          </el-select>
        </div>
        <div class="filter-block" >
          <span>班级：</span>
          <el-select clearable size="small" v-model="listQuery.checkedClass"  @change="handleCheckedClass" >
            <el-option v-for="item in  classList" :key="item.classId" :label="item.className" :value="item.classId"/>
            <div style="height: 32px;line-height: 32px; text-align: center; color: #999999; font-size: 14px" slot="empty">请先选择年级</div>
          </el-select>
        </div>

        <div class="filter-btn-area">
          <el-button type="primary" size="small" @click="fetchData(true)">查询</el-button>
          <el-button type="none" size="small" @click="initListQuery">重置</el-button>
        </div>
          <div class="ope-btn-area">
            <template v-if="permissions.indexOf('pl:personlesson:addOrEdit') !== -1">
              <el-button size="primary" type="primary" @click="$router.push({path: '/personal/courseAdd'})">新增</el-button>
            </template>
            <template v-if="permissions.indexOf('pl:personlesson:export') !== -1">
              <el-button size="primary" type="none" class="btn-none" @click="exportLesson" >导出</el-button>
            </template>
          </div>
      </div>
      <div class="calc-area" style="font-size: 14px;margin-bottom: 5px;color: #909399">
        共计 <span style="color: #02b2b5">{{pageInfo.total}}</span>条备课记录
      </div>

      <el-table ref="form" :data="tableData"  border show-overflow-tooltip style="width: 100%">
        <el-table-column
          label="序号" align="center"
          type="index"
          width="50">
        </el-table-column>
        <el-table-column  label="学期" align="center">
        <template slot-scope="scope">
            <span  class="ellipsis2" :title=" formatSchoolYear(scope.row.schoolYear, scope.row.term)">
              {{ formatSchoolYear(scope.row.schoolYear, scope.row.term)}}
            </span>
        </template>
      </el-table-column>

        <el-table-column label="标题" prop="title" align="center" >
          <template slot-scope="scope">
            <span  class="ellipsis2" :title="scope.row.title">{{scope.row.title}}</span>
          </template>
        </el-table-column>
        <el-table-column label="备课类型" align="center">
          <template slot-scope="scope">
            {{formatCourseType(scope.row.type)}}
          </template>
        </el-table-column>
        <el-table-column label="年级" prop="gradeName" align="center"/>
        <el-table-column label="班级" align="center" >
        <template slot-scope="scope">
           <span  class="ellipsis2" :title="formatClassName(scope.row.classNameStr)">
                        {{formatClassName(scope.row.classNameStr)}}
            </span>
        </template>
      </el-table-column>
        <el-table-column label="学科" prop="subjectName" align="center"/>
        <el-table-column label="创建人" prop="createName" align="center"/>

        <el-table-column label="创建时间" align="center">
          <template slot-scope="scope">
            {{scope.row.createAt | dataFormat }}
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
          show-overflow-tooltip width="220" >
          <template slot-scope="scope">
            <div class="table-ope-btn-around">
                <el-link type="primary" :underline="false" @click="$router.push({path : '/personal/courseDetail', query : {id : scope.row.id}})">查看</el-link>

              <template v-if="permissions.indexOf('pl:personlesson:addOrEdit') !== -1">
                <el-link type="primary" :underline="false" @click="$router.push({path: '/personal/courseEdit', query: {courseId: scope.row.id}})">编辑</el-link>
              </template>
              <template v-if="permissions.indexOf('pl:personpostscript:list') !== -1 && permissions.indexOf('pl:personpostscript:addOrEdit') !== -1">
                  <template v-if="scope.row.canAddPostScript == true">
                   <el-link type="primary" :underline="false" @click="$router.push({path:'/postscript/postscriptAdd', query: {courseId: scope.row.id}})">新增后记</el-link>
                 </template>
              </template>

              <template v-if="permissions.indexOf('pl:personlesson:delete') !== -1">
                <template v-if="scope.row.canDelete == true">
                  <el-link type="danger" :underline="false" @click="handleClickDelete(scope.row.id)">删除</el-link>
                </template>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.pageNum"
        :page-sizes="[10, 30 ,50]"
        :page-size="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total">
      </el-pagination>

      <el-confirm-dialog
        elTip="确定要删除吗？"
        :showDialog="cancelConfirm"
        :confirmSubmit="elConfirmDialogSubmit"
        :confirmCancel="elConfirmDialogCancel"
        @closeDialog = "elConfirmDialogClose"
      >
      </el-confirm-dialog>
    </div>
</template>

<script>
  import ElConfirmDialog from '@/components/ElConfirmDialog/index.vue'
  import {personalPlLessonList, getSubjectList, getSchoolGradeList, getSchoolClassList, deletePlLesson, getSchoolSemesterList, getTest} from '@/api/api'
  import {mapGetters} from 'vuex'
    export default {
      name: "courseList",
      components: {
        ElConfirmDialog
      },
      computed: {
        ...mapGetters([
          'permissions'
        ])
      },
        data() {
          return {
            //导出我的备课Url
            exportUrl : process.env.VUE_APP_BASE_API + "/lesson/exportPerson",
            schoolId : sessionStorage.getItem("schoolId"),
            //学科列表
            subjectList : [],
            currentSubject : '', //当前学科
            //学期列表
            semesterList: [],
            schoolSemesterList : [],
            //年级列表
            gradeTypeData: [],
            //班级列表
            classList: [],
            //查询列表
            courseList : [ {code: 1, label: "教案"},
              {code: 2, label: "单元测试分析"},
              {code: 3, label: "单元教学分析"},
              {code: 4, label: "教学计划及进度"}],
            subjectList : [],
            pickerOptionsBeginTime: {
            },
            pickerOptionsEndTime: {
            },
            pageInfo: {
              pageNum: 1,
              pageSize: 10,
              total: 0
            },
            listQuery : {
              title: '',
              createBeginTime: null,
              createEndTime: null,
              checkedSubject: '',
              checkedSemester: '',
              checkedGrade: '',
              checkedClass: '',
              distanceYear : '',
              schoolYear : '',
              term : '',
              currentSemester: {
                semesterId : '',
                schoolYear : '',
                term: '',
              },
            },
            //班级下拉是否可以使用
            classDisabled : true,
            tableData: [],
            cancelConfirm: false,
            currentDeleteId: ''
          }
        },
      methods: {
        /** 查询相关 **/
        fetchData(initPageInfo) {
         if (initPageInfo) {
           this.pageInfo.pageNum = 1;
         }
          let params = {
            pageNum : this.pageInfo.pageNum,
            pageSize : this.pageInfo.pageSize,
            title : this.listQuery.title,
            createStartTime : this.listQuery.createBeginTime,
            createEndTime : this.listQuery.createEndTime,
            subjectId : this.listQuery.checkedSubject,
            classId : this.listQuery.checkedClass,
            distanceYear : this.listQuery.checkedGrade,
            schoolYear : this.listQuery.currentSemester.schoolYear,
            term : this.listQuery.currentSemester.term,
            grade : this.listQuery.checkedGrade,
          }
          personalPlLessonList(params).then( res => {
            if (res.code == 200) {
             this.tableData = (res.result && res.result.list && Array.isArray(res.result.list)) ? res.result.list : []
              this.pageInfo.total = res.result.total || 0
            } else {
              this.$alert("获取备课列表失败！" + res.message, "错误", {type : "error"})
            }
          })


          // getPersonCourseList(param).then((res) => {
          //   if (res.code === 200) {
          //     this.tableData = res.result ? res.result.list || [] : [];
          //     this.pageInfo.total = res.result.total;
          //   } else {
          //     this.$alert("获取学生数据失败！" + res.message, "错误", {type : "error"});
          //   }
          // })
        },
        //重置查询
        initListQuery() {
          this.classList = []
          this.listQuery = {
            title: '',
            createBeginTime: null,
            createEndTime: null,
            checkedSubject: '',
            checkedSemester: '',
            checkedGrade: '',
            checkedClass: '',
            distanceYear : '',
            schoolYear : '',
            term : '',
            currentSemester: {
              semesterId : '',
              schoolYear : '',
              term: '',
            },
          }
          this.pickerOptionsEndTime = {
            disabledDate(time) {
              return null;
            }
          }
          this.pickerOptionsBeginTime = {
            disabledDate(time) {
              return null;
            }
          }
          this.fetchData(true)
        },
        changeCreateBeginTime() {
           let createBeginTime = this.listQuery.createBeginTime
          if (createBeginTime) {
            let beginTime =  new Date(createBeginTime.replace('-', '/'))
            this.pickerOptionsEndTime = {
              disabledDate(time) {
                return time.getTime() < beginTime  ;
              }
            }
          } else {
            this.pickerOptionsEndTime = {
              disabledDate(time) {
                return null ;
              }
            }
          }
        },
        changeCreateEndTime() {
          let createEndTime  = this.listQuery.createEndTime;
          if (createEndTime) {
            let endTime =   new Date(createEndTime.replace('-', '/'))
            this.pickerOptionsBeginTime = {
              disabledDate(time) {
                return time.getTime() > endTime ;
              }
            }
          } else {
            this.pickerOptionsBeginTime = {
              disabledDate(time) {
                return null ;
              }
            }
          }

        },
        // 格式化学年信息
        formatSchoolYear(schoolYear, schoolTerm) {
          let year = parseInt(schoolYear) + parseInt(1)
          let term = schoolTerm == 1 ? "第一学期" : "第二学期"
          return `${schoolYear}年-${year}年${term}`
        },
        //格式化班级信息
        formatClassName(strArr) {
          if (strArr == undefined) {
            return
          }
          let classArr = strArr.split(",")
          let classNameStr = ""
          if (classArr.length > 0) {
            classArr.forEach(item => {
              classNameStr = classNameStr + `${item}班， `
            })
            let index = classNameStr.length - 2
            classNameStr = classNameStr.slice(0, index)
          }
          return classNameStr
        },
        //选择年级变化后 ，班级相应变化
        handleCheckedGrade() {
          let distanceYear = this.listQuery.checkedGrade;
          if (isNaN(parseInt(this.listQuery.checkedGrade))) {
            this.classList = []
            this.listQuery.checkedClass = ''
            return
          }
          this.fetchData(true)
          let tempGrade = this.getGradeMsgByDistanceYear(this.listQuery.checkedGrade);
          if (tempGrade == null) {
            this.classList = []
            return ;
          }
          let params = {
            grade : tempGrade.name,
            distanceYear: tempGrade.distanceYear
          }
          getSchoolClassList(params).then(res => {
            if (res.code == 200) {
              this.classList = res.result || []

            } else {
              this.$alert('学校还未维护该年级下班级信息，请联系华育技术支持进行初始化！', '提示', {
                confirmButtonText: '我知道了',
              });
            }
          })
        },
        //切换班级
        handleCheckedClass() {
          // if (!this.listQuery.checkedGrade || this.classList.length == 0) {
          //   this.$message.warning("请先选择年级！");
          // } else {
          //   this.fetchData(true)
          // }
          this.fetchData(true)
        },
        /** 查询相关结束 **/
        /** 分页相关 **/
        handleSizeChange(val) {
          this.pageInfo.pageSize = val
          this.fetchData()
        },
        handleCurrentChange(val) {
          this.pageInfo.pageNum = val
          this.fetchData()
        },
        /** 分页相关结束**/

        /** 枚举格式化**/
        formatCourseType(code) {
          for (let item of this.courseList) {
            if (item.code == code ) {
              return item.label;
            }
          }
          return "";
        },
        formatSubjectType(code) {
          for (let item of this.subjectList) {
            if (item.value == code ) {
              return item.label;
            }
          }
          return "";
        },
        /** 枚举格式化结束**/

        //点击取消按钮
        handleClickDelete(id) {
          if(!id) {
            return
          }
          this.currentDeleteId = id;
          this.cancelConfirm = true
        },
        /** 取消询问框相关**/
        elConfirmDialogSubmit() {
          // this.initAddCourseForm()
          let params = {
            lessonId : this.currentDeleteId
          }
          deletePlLesson(params).then(res => {
            if (res.code == 200) {
              this.$message.success("删除备课成功！");
              this.fetchData(true)
              this.cancelConfirm = false
            } else {
              this.$alert("删除备课失败！" + res.message, "错误", {type : "error"})
            }
          })
          this.$router.push("/personal/courseList")
        },
        elConfirmDialogCancel() {
          this.cancelConfirm = false
        },
        elConfirmDialogClose() {
          this.cancelConfirm = false
        },
        /** 取消询问框相关结束**/

        /**  初始化 **/
        //初始化学科信息
        initSubjectList() {
          let params = {}
          getSubjectList(params).then(res => {
            if(res.code == 200) {
              this.subjectList = this.formatSubjectList(res.result)
            } else {
              this.$alert("获取学科数据失败！" + res.message, "错误", {type : "error"})
            }
          })
        },
        //格式化学科信息
        formatSubjectList(array) {
          if(!array || !Array.isArray(array) || array.length <= 0) {
            this.$alert('学校还未维护学科选项信息，请联系华育技术支持进行初始化！', '提示', {
              confirmButtonText: '我知道了',
            });
            return []
          }
          let tempArr = []
          array.forEach(item => {
            let tempItem = {
              subjectId: item.id,
              subjectName : item.name,
              subjectCode : item.code,
              subjectType : item.type,
              subjectLevel :  item.level
            }
            tempArr.push(tempItem)
          })
          return tempArr
        },
        //年级初始化
        initGradeList() {
          this.gradeTypeData= []
          getSchoolGradeList().then(res => {
            if (res.code === 200) {
              if (res.result && res.result.length && res.result.length > 0) {
                this.gradeTypeData = res.result;
              } else {
                this.$alert('学校还未维护年级选项信息，请联系华育技术支持进行初始化！', '提示', {
                  confirmButtonText: '我知道了',
                });
              }
            } else {
              this.$alert("获取年级选项列表失败！" + res.message, "错误", {type : "error"})
            }
          })
        },
        // 根据年级distanceYear获取年级详情
        getGradeMsgByDistanceYear(code) {
          if (this.gradeTypeData && this.gradeTypeData.length && this.gradeTypeData.length > 0) {
            for (let item of this.gradeTypeData) {
              if (item.distanceYear == code) {
                return item;
              }
            }
          }
          return null;
        },
        handleChangeSemester() {
          if (this.schoolSemesterList.length < 0){
            return null
          }
          for (let item of this.schoolSemesterList) {
            if (item.code == this.listQuery.checkedSemester) {
              if (item.code.length >= 5 ) {
                this.listQuery.currentSemester.semesterId = item.semesterId
                this.listQuery.currentSemester.schoolYear = item.code.substr(0, 4)
                this.listQuery.currentSemester.term = item.code.substr(4, 1)
              }
            }
          }
          this.fetchData(true)
        },
        initSchoolSemester() {
          getSchoolSemesterList().then(res => {
            if ( res.code == 200) {
              if (res.result && Array.isArray(res.result) && res.result.length > 0) {
                let tempSemesterList  = res.result
                tempSemesterList.forEach(semesterItem => {
                  let year = parseInt(semesterItem.schoolYear) + parseInt(1)
                  let term = semesterItem.term == 1 ? "第一学期" : "第二学期"
                  let label   =  `${parseInt(semesterItem.schoolYear)}年-${year}年${term}`
                  let code = `${semesterItem.schoolYear}${semesterItem.term}`
                  let semesterId = semesterItem.id
                  this.schoolSemesterList.push({label, code, semesterId})
                  this.schoolSemesterList.sort(this.compare('code'))
                })
              } else {
                this.$alert('学校还未维护学年学期信息，请联系华育技术支持进行添加！', '提示', {
                  confirmButtonText: '我知道了',
                });
              }
            } else {
              this.$alert("获取学年学期数据失败！" + res.message, "错误", {type: "error"})
            }
          })

        },
        //导出我的备课
        exportLesson() {
          let url = this.exportUrl + "?schoolToken=" + sessionStorage.getItem("schoolId") + "&title=" + this.listQuery.title
            + "&createStartTime=" +this.listQuery.createBeginTime + "&createEndTime=" + this.listQuery.createEndTime
            + "&subjectId=" + this.listQuery.checkedSubject + "&classId=" + this.listQuery.checkedClass
            +  "&distanceYear=" + this.listQuery.checkedGrade + "&schoolYear=" + this.listQuery.currentSemester.schoolYear
            +  "&term=" + this.listQuery.currentSemester.term + "&grade=" + this.listQuery.checkedGrade
          window.open(url)
        },
        compare (propertyName) {
          return function (object1, object2) {
            let value1 = object1[propertyName]
            let value2 = object2[propertyName]
            if (value2 > value1) {
              return 1
            } else if (value2 < value1) {
              return -1
            } else {
              return 0
            }
          }
        }
        /**  初始化结束 **/

      },
      mounted () {
        this.initSubjectList()
        this.initGradeList()
        this.initSchoolSemester()
        this.fetchData(true)

      },
      created() {

      },
    }
</script>

<style scoped>

</style>
